<?php

class Job_model extends MY_Model{
    
    public function __construct() {
	parent::__construct();
	
	$this->table = 'jd_job';
    }
    
    public function frontend_records($limit = 0, $offset = 0,$conditions = array()){
	$lang = $this->input->cookie('lang');
	
	if($lang == 'en'){
	    $this->db->select('id,position_en as position,requirements_en as requirements,order,created_at');
	}else{
	    $this->db->select('id,position,requirements,order,created_at');
	}
	
	$this->db->from($this->table);
	
	if(isset($conditions[0])){
            foreach($conditions as $condition){
                $this->db->where($condition[0],$condition[1]);
            }
        }
        
        if($limit){
            $this->db->limit($limit,$offset);
        }
        
        $this->db->order_by('order','desc');
        
        $query = $this->db->get();
        
        return $query->result();
    }
    
    public function frontend_find($id){
	$lang = $this->input->cookie('lang');
	
	if($lang == 'en'){
	    $this->db->select('id,position_en as position,requirements_en as requirements,order,created_at');
	}else{
	    $this->db->select('id,position,requirements,order,created_at');
	}
	
	$this->db->where('id',$id);
	
	$this->db->from($this->table);
	
	$this->db->limit(1);
	
	$query = $this->db->get();
	
	return $query->row();
    }
    
    public function order($id, $new_order) {
	$job = $this->find($id);

	if ($job->order > $new_order) {
	    $end_order = $job->order - 1;

	    $sql = "update `{$this->table}` 
            set `order`=`order`+1 
            where `order`>={$new_order} 
            and `order`<={$end_order};";
	} else {
	    $start_order = $job->order + 1;

	    $sql = "update `{$this->table}`
            set `order`=`order`-1 
            where `order`>='{$start_order}' 
            and `order`<='{$new_order}';";
	}

	$this->db->query($sql);

	return $this->update($id, array('order' => $new_order));
    }

    public function max_order() {
	$sql = "select max(`order`) as max_order from `{$this->table}`";

	$query = $this->db->query($sql);

	return $query->row_object()->max_order;
    }
}